package com.mfp.java.testYou.ui.mvc;

import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.mfp.java.testYou.core.AppContext;
import com.mfp.java.testYou.core.servlets.ManageUserServlet;
import com.mfp.java.testYou.db.model.User;
import com.mfp.java.testYou.db.model.UserRole;
import com.mfp.java.testYou.model.Language;

public class UserPage extends AbstractMVC {

	private static final Logger log = Logger.getLogger(UserPage.class);

	public static final String URL = "/testYou/pages/user.jsp";

	public static final String ATTR_EDIT_USER = "editableUser";

	private User user;

	public UserPage(HttpServletRequest request, HttpServletResponse response) {
		super(request, response);
		init();
	}

	private void init() {
		try {
			Object o = getRequest().getAttribute(ATTR_EDIT_USER);
			if (o == null) {
				log.debug("No user found in request. Page is new User Page");
				user = null;
				return;
			} else {
				log.debug("User data found. Page is edit User Page");
			}
			user = (User) o;
		} catch (ClassCastException e) {
			log.error("Could not cast user class. Make sure to add user class as request attribute");
		}
	}

	public List<Language> getLangs() {
		return AppContext.getLangs();
	}

	public List<String> getRoles() {
		List<String> list = new LinkedList<String>();
		for (UserRole role : UserRole.values()) {
			list.add(role.name());
		}
		return list;
	}

	public boolean isEdit() {
		return user != null;
	}

	public String getOperationName() {
		return isEdit() ? ManageUserServlet.OPERATION_CHANGE : ManageUserServlet.OPERATION_ADD;
	}

	public String getUsername() {
		return isEdit() ? user.getUserName() : "";
	}


    public String getPass(){
        return isEdit() ? user.getPassword() : "";
    }

	public Integer getUserLangIndex() {
		if (!isEdit()) {
			return 0;
		}
		List<Language> langs = getLangs();
		for (int i = 0; i < langs.size(); i++) {
			if (langs.get(i).getId().equals(user.getLang())) {
				return i;
			}
		}
		log.warn("Could not find user language index (for: " + user.getLang() + "). Using 0");
		return 0;
	}

	public Integer getUserRoleIndex() {
		if (!isEdit()) {
			return 0;
		}
		List<String> roles = getRoles();
		for (int i = 0; i < roles.size(); i++) {
			if (roles.get(i).equals(user.getRole().name())) {
				return i;
			}
		}
		log.warn("Could not find user role index. Using 0");
		return 0;
	}

	public Integer getId() {
		return isEdit() ? user.getId() : 0;
	}

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}
